<?php
include '../../system/libraries/database.php';
include '../../system/core/utils.php';
require_once('../../system/models/UserSession.class.php');
require_once('../../system/models/User.class.php');

$response = array();

$action = $_POST['action'];
if($action != 'logout')
{
  $email = $_POST['email'];
  $password = md5($_POST['password']);
}

function Validate($value)
{
  if(preg_match('/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/', $value))
    return true;

  return false;
}

if ($action == 'user-registration')
{
  $userName = $_POST['displayName'];
  if($userName && Validate($email))
  {
    $user = new User();
    $user->displayName = $userName;
    $user->email = $email;
    $user->password = $password;
    $user->type = 'user';
    $user->Save();
    session_start();
    $_SESSION['name'] = $user->displayName;
    $message['code'] = 200;
  }
}
else
  if($action == 'user-logIn')
  {
    $user = new User(null, $email);
    if ($user->id > 0)
    {
      if(Validate($email) && $user->ValidateCredentials($email, $password))
      {
        $message['code'] = 200;
        session_start();
        $_SESSION['name'] = $user->displayName;
      }
      else
      {
        $message['message'] = 'Email sau parola introdusa nu este corecta!';
      } 
    }
    else
      $message['message'] = 'Adresa de email introdusă nu este corectă!';
  }
else
  if($action == 'logout')
  {
    session_start();
    session_destroy ();
    $message['code'] = 200;
  }
  else
    $message['message'] = 'Something wrong!'; 

print json_encode($message);


?>